#!/bin/bash
echo "===== 免密登陆 ====="

# 删除原有
rm -f /root/.ssh/id_rsa
rm -f /root/.ssh/id_rsa.pub


# 嵌入执行
/usr/bin/expect <<-EOF
spawn ssh-keygen -t rsa
expect {
    "Enter file in which to save the key (/root/.ssh/id_rsa):" {send "\r";exp_continue}
    "Enter passphrase (empty for no passphrase):" {send "\r";exp_continue}
    "Enter same passphrase again:" {send "\r"}
}
expect eof
EOF

#>>>>>>>>>>>>>>>>>>>>>> 取hosts中主机开始 >>>>>>>>>>>>>>>>>>>>>>>>>>>>
USER=`whoami`
FILE_DIR=/root/.ssh
SELF_HOST_NAME=$(hostname)
#IFS设置IFS环境变量，这个变量是用来定义分隔符类型的。默认的分隔符为空格、换行符、tab。
IFS_old=$IFS
IFS=$'\n'
for host in `grep -v localhost /etc/hosts | awk '{print($2)}'`; do
    # echo "$FILE_DIR/$FILE_NAME $USER@$host:$FILE_DIR"
    # ssh-copy-id -i $FILE_DIR/id_rsa.pub $USER@$host
    /usr/bin/expect <<-EOF
    spawn /usr/bin/ssh-copy-id -i $FILE_DIR/id_rsa.pub $USER@$host
    expect {
        "Are you sure you want to continue connecting (yes/no)?" {send "yes\r";exp_continue}
        "*password:" {send "000\r"}
    }
    expect eof
EOF
done
#将IFS变量还原为默认值
IFS=$IFS_old
#>>>>>>>>>>>>>>>>>>>>>> 取hosts中主机结束 >>>>>>>>>>>>>>>>>>>>>>>>>>>>